<template>
  <div v-if="inEdit">
    <!-- https://blog.csdn.net/Piqzem/article/details/88908096 -->
    <!-- 限制element-ui表单中input框只能输入数字和小数点 -->
    <!-- @input.native="data=data.replace(/[^\d.]/g,'')" -->
    <!-- @keyup.enter.native="onEnter" -->
    <el-input
      ref="input"
      v-model="data"
      :type="type"
      autosize
      placeholder="*多种*"
      size="mini"
      :clearable="true"
      :show-password="password"
      @change="onChange"
      @blur="onBlur"
    />
  </div>
  <div v-else class="no-edit-text">{{ label }}</div>
</template>

<script>
import props from '../mixins/props'
export default {
  name: 'PropertyString',
  mixins: [props],
  props: {
    // 是否多行
    multiline: {
      type: Boolean,
      required: false,
      default: false
    },
    // 是否按密码格式显示
    password: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {
      data: undefined
    }
  },
  computed: {
    type() {
      if (this.password) {
        return 'text'
      } else if (this.multiline) {
        return 'textarea'
      } else {
        return 'text'
      }
    },
    label() {
      if (typeof this.data !== 'string') {
        return '*多种*'
      } else if (this.password) {
        let s = ''
        for (let i = 0; i < this.data.length; i++) {
          s += '•'
        }
        return s
      } else {
        return this.data
      }
    }
  },
  watch: {
    value(val) {
      if (val === null || val === undefined) {
        this.data = undefined
      } else {
        this.data = val.toString()
      }
    }
  },
  created() {
    if (this.value === null || this.value === undefined) {
      this.data = undefined
    } else {
      this.data = this.value.toString()
    }
  },
  methods: {
    onChange(val) {
      // 更新data数据
      // this.data = val
      // 向父组件发送change消息(参数需转换为json字符串!!!)
      this.$emit('change', val)
    },
    onEnter(event) {
      this.data = event.target.value
      if (this.data !== undefined && this.data !== null) {
        this.$emit('change', this.data.toString())
      }
    },
    onBlur(event) {
      // console.log('string.vue 失去焦点')
      if (this.inEdit) {
        // 强行夺回焦点
        this.$refs.input.focus()
      }
    }
  }
}
</script>
